package com.kuangjia.student_ems.service.impl;

import com.kuangjia.student_ems.service.EmailCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 邮箱验证码服务实现类
 */
@Service
public class EmailCodeServiceImpl implements EmailCodeService {

    private static final Logger logger = LoggerFactory.getLogger(EmailCodeServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Value("${verification.code.expire-minutes:5}")
    private int expireMinutes;
    
    @Value("${verification.code.length:6}")
    private int codeLength;
    
    @Value("${verification.code.resend-interval-seconds:60}")
    private int resendInterval;
    
    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public boolean sendEmailCode(String email) {
        try {
            // 检查是否可以重新发送
            if (!canResendEmailCode(email)) {
                logger.warn("邮箱 {} 验证码发送过于频繁", email);
                return false;
            }
            
            // 生成验证码
            String code = generateCode();
            logger.info("为邮箱 {} 生成验证码: {}", email, code);
            
            // 存储到Redis，设置过期时间
            String key = "email_code:" + email;
            redisTemplate.opsForValue().set(key, code, expireMinutes, TimeUnit.MINUTES);
            
            // 设置重发限制
            String resendKey = "email_resend_limit:" + email;
            redisTemplate.opsForValue().set(resendKey, "1", resendInterval, TimeUnit.SECONDS);
            
            // 发送邮件
            sendEmail(email, code);
            
            logger.info("邮箱 {} 验证码发送成功", email);
            return true;
        } catch (Exception e) {
            logger.error("邮箱 {} 验证码发送失败", email, e);
            return false;
        }
    }

    @Override
    public boolean verifyEmailCode(String email, String code) {
        try {
            String key = "email_code:" + email;
            String storedCode = redisTemplate.opsForValue().get(key);
            
            if (storedCode != null && storedCode.equals(code)) {
                // 验证成功后删除验证码
                redisTemplate.delete(key);
                logger.info("邮箱 {} 验证码验证成功", email);
                return true;
            }
            
            logger.warn("邮箱 {} 验证码验证失败，输入: {}, 存储: {}", email, code, storedCode);
            return false;
        } catch (Exception e) {
            logger.error("邮箱 {} 验证码验证异常", email, e);
            return false;
        }
    }

    @Override
    public boolean canResendEmailCode(String email) {
        String resendKey = "email_resend_limit:" + email;
        return redisTemplate.opsForValue().get(resendKey) == null;
    }

    /**
     * 生成6位数字验证码
     */
    private String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < codeLength; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 发送验证码邮件（HTML美化版）
     */
    private void sendEmail(String email, String code) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setFrom(fromEmail);
            helper.setTo(email);
            helper.setSubject("员工管理系统 - 邮箱验证码");

            String html = String.format(
                "<div style='font-family:微软雅黑,Arial,sans-serif;font-size:16px;color:#333;'>"
                + "<h2 style='color:#1976d2;'>员工管理系统</h2>"
                + "<p>尊敬的用户，您好！</p>"
                + "<p>您的邮箱验证码为：</p>"
                + "<div style='font-size:28px;font-weight:bold;letter-spacing:8px;color:#1976d2;margin:16px 0;'>%s</div>"
                + "<p>验证码有效期：<b>%d 分钟</b></p>"
                + "<p style='color:#888;'>请在规定时间内完成操作。如非本人操作，请忽略此邮件。</p>"
                + "<div style='margin-top:24px;font-size:14px;color:#aaa;'>—— 员工管理系统团队</div>"
                + "</div>",
                code, expireMinutes
            );

            helper.setText(html, true); // true表示HTML内容
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            logger.error("发送HTML验证码邮件失败", e);
        }
    }
} 